﻿using NoteHelper.IBusiness;
using NoteHelper.Utils;
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using Unity;

namespace NoteHelper.Account
{
    public partial class Acfl001 : WeifenLuo.WinFormsUI.Docking.DockContent,IBaseView
	{
        private const string Pre = "Acfl_";
		private log4net.ILog logger;
		private DevAge.ComponentModel.IBoundList bd;
		public Acfl001()
		{
			InitializeComponent();
		}

		private void Acfl001_Load(object sender, EventArgs e)
		{
			logger = log4net.LogManager.GetLogger("NoteHelper.Account.Acfl001");
            var container = UnityHelper.GetContainer();
            var accountFlowManager = container.Resolve<IAccountFlowManager>();
            var accountTable = accountFlowManager.GetAccountList();
            Acfl_AccountId.DataSource = accountTable;
            Acfl_AccountId.DisplayMember = "Name";
            Acfl_AccountId.ValueMember = "Id";

            var accountTable2 = accountTable.Copy();
            Acfl_ToAccountId.DataSource = accountTable2;
            Acfl_ToAccountId.DisplayMember = "Name";
            Acfl_ToAccountId.ValueMember = "Id";
            var flowTypes = accountFlowManager.GetBizTypeList();
            Acfl_BizType.DataSource = flowTypes;
            Acfl_BizType.DisplayMember = "text";
            Acfl_BizType.ValueMember = "id";

            displayGrid.FixedRows = 1;
            displayGrid.FixedColumns = 1;
            CreateColumns(accountTable, flowTypes);
            var controller = new Acfl001Controller(this, accountFlowManager);
        }
        private void CreateColumns(DataTable accountTable, DataTable flowTypes)
        {
            DevAge.Drawing.RectangleBorder border = new DevAge.Drawing.RectangleBorder(new DevAge.Drawing.BorderLine(Color.ForestGreen), new DevAge.Drawing.BorderLine(Color.ForestGreen));

            PopupMenu popupMenu = new PopupMenu();
            popupMenu.AddMenuItems("全选", SelectAll);
            popupMenu.AddMenuItems("取消", UnSelectAll);
            popupMenu.AddMenuItems("反选", TaggleSelect);
            SourceGrid.DataGridColumn gridColumn;
            gridColumn = displayGrid.Columns.Add("FlowSeq", "流水", typeof(string));
            gridColumn.HeaderCell.AddController(popupMenu);
            gridColumn.Width = 50;

            gridColumn = AccountFormatter(accountTable);

            string dtFormat2 = "yyyy-MM-dd";
            string[] dtParseFormats = new string[] { dtFormat2 };
            System.Globalization.DateTimeStyles dtStyles = System.Globalization.DateTimeStyles.AllowInnerWhite | System.Globalization.DateTimeStyles.AllowLeadingWhite | System.Globalization.DateTimeStyles.AllowTrailingWhite | System.Globalization.DateTimeStyles.AllowWhiteSpaces;
            TypeConverter dtConverter = new DevAge.ComponentModel.Converter.DateTimeTypeConverter(dtFormat2, dtParseFormats, dtStyles);
            SourceGrid.Cells.Editors.TextBoxUITypeEditor editorDt2 = new SourceGrid.Cells.Editors.TextBoxUITypeEditor(typeof(DateTime));
            editorDt2.TypeConverter = dtConverter;
            gridColumn = displayGrid.Columns.Add("HappenDate", "发生日期", editorDt2);
            gridColumn.Width = 80;
            gridColumn = displayGrid.Columns.Add("Description", "备注", typeof(string));
            gridColumn.Width = 200;

            gridColumn = FlowTypeFormatter(flowTypes);

            SourceGrid.Cells.Views.Cell viewRight = new SourceGrid.Cells.Views.Cell();
            viewRight.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            viewRight.Border = border;

            SourceGrid.Cells.Editors.TextBox currencyEditor = new SourceGrid.Cells.Editors.TextBox(typeof(decimal));
            currencyEditor.TypeConverter = new DevAge.ComponentModel.Converter.CurrencyTypeConverter(typeof(decimal));
            gridColumn = displayGrid.Columns.Add("Amount", "发生金额", currencyEditor);
            gridColumn.DataCell.View = viewRight;
            gridColumn.Width = 100;
            gridColumn = displayGrid.Columns.Add("LeftAmount", "期末余额", currencyEditor);
            gridColumn.DataCell.View = viewRight;
            gridColumn.Width = 100;

            // 创建显示的样式
            SourceGrid.Cells.Views.Cell flowOutView = new SourceGrid.Cells.Views.Cell();
            flowOutView.BackColor = Color.DarkSeaGreen;
            flowOutView.Border = border;

            SourceGrid.Cells.Views.Cell viewNumeric = new SourceGrid.Cells.Views.Cell();
            viewNumeric.BackColor = Color.DarkSeaGreen;
            viewNumeric.Border = border;
            viewNumeric.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;


            // 创建条件判断
            SourceGrid.Conditions.ConditionView condition1 = new SourceGrid.Conditions.ConditionView(flowOutView);
            condition1.EvaluateFunction = delegate (SourceGrid.DataGridColumn column, int gridRow, object itemRow)
            {
                DataRowView row = (DataRowView)itemRow;
                return row["BizType"].ToString() == "-1";
            };
            SourceGrid.Conditions.ConditionView condition2 = new SourceGrid.Conditions.ConditionView(viewNumeric);
            condition2.EvaluateFunction = delegate (SourceGrid.DataGridColumn column, int gridRow, object itemRow)
            {
                DataRowView row = (DataRowView)itemRow;
                return row["BizType"].ToString() == "-1";
            };

            foreach (SourceGrid.DataGridColumn col in displayGrid.Columns)
            {
                if (col.PropertyName == "Amount" || col.PropertyName == "LeftAmount")
                {
                    col.Conditions.Add(condition2);
                }
                else
                {
                    col.Conditions.Add(condition1);
                }
            }
        }

        private SourceGrid.DataGridColumn AccountFormatter(DataTable table)
        {
            int count = table.Rows.Count;
            string[] standardValues = new string[count];
            string[] displayNames = new string[count];
            for (int i = 0; i < count; i++)
            {
                DataRow row = table.Rows[i];
                standardValues[i] = row["Id"].ToString();
                displayNames[i] = row["Name"].ToString();
            }
            var editor = new SourceGrid.Cells.Editors.ComboBox(typeof(string));
            editor.StandardValues = standardValues;
            editor.StandardValuesExclusive = true;
            editor.Control.FormattingEnabled = true;

            var mapping = new DevAge.ComponentModel.Validator.ValueMapping();
            mapping.ValueList = standardValues;
            mapping.DisplayStringList = displayNames;
            mapping.BindValidator(editor);
            var gridColumn = displayGrid.Columns.Add("AccountId", "主账号", editor);
            gridColumn.Width = 100;
            return gridColumn;
        }
        
        private SourceGrid.DataGridColumn FlowTypeFormatter(DataTable table)
        {
            int count = table.Rows.Count;
            int[] standardValues = new int[count];
            string[] displayNames = new string[count];
            for (int i = 0; i < count; i++)
            {
                DataRow row = table.Rows[i];
                standardValues[i] = (int)row["id"];
                displayNames[i] = row["text"].ToString();
            }
            var editor = new SourceGrid.Cells.Editors.ComboBox(typeof(int));
            editor.StandardValues = standardValues;
            editor.StandardValuesExclusive = true;
            editor.Control.FormattingEnabled = true;

            var mapping = new DevAge.ComponentModel.Validator.ValueMapping();
            mapping.ValueList = standardValues;
            mapping.DisplayStringList = displayNames;
            mapping.BindValidator(editor);
            var gridColumn = displayGrid.Columns.Add("BizType", "业务类型", editor);
            gridColumn.Width = 80;
            return gridColumn;
        }
        #region ==== IBaseView Impl ====

        private DataTable _displayList;
		public DataTable DisplayList
		{
			get { return _displayList; }
			set
			{
				if (value == null) return;
				_displayList = value;
				
				bd = new DevAge.ComponentModel.BoundDataView(_displayList.DefaultView);
				bd.AllowNew = false;
				bd.AllowEdit = false;
				bd.AllowDelete = false;
				displayGrid.DataSource = bd;
			}
		}
		public FormCommand Cmd { get; set; }
        public Hashtable RowData
        {
            get
            {
                return splitContainer1.Panel1.GetData(Pre);
            }
            set
            {
                splitContainer1.Panel1.SetData(Pre, value);
            }
        }
        public event EventHandler Insert;
		public event EventHandler Edit;
		public event EventHandler Remove;
		public event EventHandler Copy;
		public event EventHandler Query;
		public event EventHandler Accept;
		public event EventHandler Cancel;
		public event EventHandler Print;
		public event EventHandler Help;
		public void BeginEdit()
        {
            splitContainer1.Panel1.ChangeInputState(Pre, true);
        }
		public void EndEdit()
        {
            splitContainer1.Panel1.ChangeInputState(Pre, false);
        }
		public int GetRowIndex()
		{
			int rowIndex = -1;
			object[] rows = displayGrid.SelectedDataRows;
			if (rows != null && rows.Length > 0)
			{
				DataRowView row = (DataRowView)rows[0];
				int.TryParse(row["$_rowIndex"].ToString(), out rowIndex);
			}
			return rowIndex;
		}
		

		#endregion

		#region ==== Toolbar Event ====
		/// <summary>
		/// 添加
		/// </summary>
		private void InsertButtonClick(object sender, EventArgs e)
		{
			Insert?.Invoke(sender, e);
		}
		/// <summary>
		/// 修改
		/// </summary>
		private void EditButtonClick(object sender, EventArgs e)
		{
			Edit?.Invoke(sender, e);
		}
		/// <summary>
		/// 删除
		/// </summary>
		private void RemoveButtonClick(object sender, EventArgs e)
		{
			Remove?.Invoke(sender, e);
		}
		/// <summary>
		/// 复制
		/// </summary>
		private void CopyButtonClick(object sender, EventArgs e)
		{
			Copy?.Invoke(sender, e);
		}
		/// <summary>
		/// 查询
		/// </summary>
		private void QueryButtonClick(object sender, EventArgs e)
		{
			Query?.Invoke(sender, e);
		}
		/// <summary>
		/// 确定
		/// </summary>
		private void AcceptButtonClick(object sender, EventArgs e)
		{
			Accept?.Invoke(sender, e);
		}
		/// <summary>
		/// 取消
		/// </summary>
		private void CancelButtonClick(object sender, EventArgs e)
		{
			Cancel?.Invoke(sender, e);
		}
		/// <summary>
		/// 打印
		/// </summary>
		private void PrintButtonClick(object sender, EventArgs e)
		{
			Print?.Invoke(sender, e);
		}
		/// <summary>
		/// 帮助
		/// </summary>
		private void HelpButtonClick(object sender, EventArgs e)
		{
			Help?.Invoke(sender, e);
        }
        private void SelectAll(object sender, EventArgs e)
        {
        }
        private void UnSelectAll(object sender, EventArgs e)
        {
        }
        private void TaggleSelect(object sender, EventArgs e)
        {
        }

        public void Notify(string notification)
        {
            AlterMsg.Info(notification);
        }
        #endregion
    }
}
